import { Button, VerticalBox , HorizontalBox, TabWidget, ListView, StandardListView, StandardTableView, CheckBox, ScrollView} from "std-widgets.slint";
import {TypeOfOpenedItem} from "common.slint";
import {ColorPalette} from "color_palette.slint";
import {MainListModel} from "common.slint";
import {Callabler} from "callabler.slint";
import {GuiState} from "gui_state.slint";

export component SelectableTableView inherits Rectangle {
    in property <[string]> columns;
    in-out property <[MainListModel]> values: [
        {checked: false, selected_row: false, header_row: true, filled_header_row: false, val_str: ["kropkarz", "/Xd1", "24.10.2023"], val_int: []} ,
        {checked: false, selected_row: false, header_row: false, filled_header_row: false, val_str: ["witasphere", "/Xd1/Imagerren2", "25.11.1991"], val_int: []} ,
        {checked: false, selected_row: false, header_row: false, filled_header_row: false, val_str: ["witasphere", "/Xd1/Imagerren2", "25.11.1991"], val_int: []} ,
        {checked: true, selected_row: false, header_row: false, filled_header_row: false, val_str: ["lokkaler", "/Xd1/Vide2", "01.23.1911"], val_int: []}
    ];
    in-out property <[length]> column_sizes: [30px, 80px, 150px, 160px];
    private property <int> column_number: column_sizes.length + 1;
    // This idx, starts from zero, but since first is always a checkbox, and is not in model.val values, remove 1 from idx
    in-out property <int> parentPathIdx;
    in-out property <int> fileNameIdx;
    in-out property <int> start_shift_idx: -1;
    in-out property <int> last_selected_idx: -1;
    out property <length> item_height: 20px;

    out property <length> list_view_width: max(self.width - 20px, column_sizes[0] + column_sizes[1] + column_sizes[2] + column_sizes[3] + column_sizes[4] + column_sizes[5] + column_sizes[6] + column_sizes[7] + column_sizes[8] + column_sizes[9] + column_sizes[10] + column_sizes[11]);

    VerticalBox {
        padding: 0px;
        ScrollView {
            height: 30px;
            viewport-x <=> list_view.viewport-x;
            vertical-stretch: 0;

            HorizontalLayout {
                spacing: 5px;
                for title[idx] in root.columns: HorizontalLayout {
                    width: root.column_sizes[idx];
                    Text {
                        overflow: elide;
                        text: title;
                    }

                    Rectangle {
                        width: 1px;
                        background: gray;
                        TouchArea {
                            width: 8px;
                            x: (parent.width - self.width) / 2;
                            property <length> cached;
                            pointer-event(event) => {
                                if (event.button == PointerEventButton.left && event.kind == PointerEventKind.down) {
                                    self.cached = root.column_sizes[idx];
                                }
                            }
                            moved => {
                                if (self.pressed) {
                                    root.column_sizes[idx] += (self.mouse-x - self.pressed-x);
                                    if (root.column_sizes[idx] < 20px) {
                                        root.column_sizes[idx] = 20px;
                                    }
                                }
                            }
                            mouse-cursor: ew-resize;
                        }
                    }
                }
            }
        }

        list_view := ListView {
            padding: 0px;
            min-width: 100px;
            for r[idx] in root.values: Rectangle {
                width: list_view_width;
                border-radius: 5px;
                height: item_height;
                background: ColorPalette.get_listview_color_with_header(r.selected_row, touch-area.has-hover, r.header_row);
                touch_area := TouchArea {
                    double-clicked => {
                        Callabler.row_open_selected_item();
                    }
                    pointer-event(event) => {
                        if (event.button == PointerEventButton.right && event.kind == PointerEventKind.up) {
                            Callabler.row_reverse_single_unique_item(idx);
                            Callabler.row_open_parent_of_selected_item();
                        } else if (event.button == PointerEventButton.left && event.kind == PointerEventKind.up) {
                            if (event.modifiers.control) {
                                start_shift_idx = idx;
                                Callabler.row_reverse_item_selection(idx);
                                hidePreview();
                            } else if (event.modifiers.shift) {
                                if (start_shift_idx == -1) {
                                    start_shift_idx = idx;
                                }
                                Callabler.row_select_items_with_shift(idx, start_shift_idx);

                                if (start_shift_idx == idx) {
                                    showPreview(idx);
                                } else {
                                    hidePreview();
                                }
                            } else {
                                start_shift_idx = idx;
                                Callabler.row_reverse_single_unique_item(idx);
                                showPreview(idx);
                            }

                            last_selected_idx = idx;
                        }
                    }
                }

                HorizontalLayout {
                    CheckBox {
                        visible: !r.header_row;
                        checked: r.checked && !r.header_row;
                        width: root.column_sizes[0];
                        toggled => {
                            r.checked = self.checked;
                        }
                    }

                    HorizontalLayout {
                        spacing: 5px;
                        for f[idx] in r.val_str: Text {
                            width: root.column_sizes[idx + 1];
                            text: f;
                            font-size: 12px;
                            vertical-alignment: center;
                            overflow: elide;
                        }
                    }
                }
            }
        }
    }

    // Already rust code should deal with selections in the model, but this one is not able to handle
    public function reset_selection() {
        start_shift_idx = -1;
        last_selected_idx = -1;
        hidePreview();
    }

    function contains_data(idx: int) -> bool {
        return root.values[idx].val_str.length > 0;
    }

    function position_to_item(idx: int) {
        if (idx * item_height < -list_view.viewport-y) {
            list_view.viewport-y = - (idx * item_height - 10px);
        } else if ((idx + 1) * item_height > -list_view.viewport-y + list_view.height) {
            list_view.viewport-y = - ((idx + 1) * item_height - list_view.height + 10px);
        }
    }

    function get_number_of_items_to_skip() -> int {
        list_view.height / item_height;
    }

    function jump_up(modifiers: KeyboardModifiers, items: int) {
        if (last_selected_idx != -1) {
            last_selected_idx = (last_selected_idx - items).max(0);
            // If hit at header, try to skip it
            if (!contains_data(last_selected_idx)) {
                last_selected_idx = (last_selected_idx - 1).max(0);
            }

            if (!modifiers.shift) {
                start_shift_idx = last_selected_idx;
            }
            
            Callabler.row_select_items_with_shift(start_shift_idx, last_selected_idx);
            if (start_shift_idx == last_selected_idx) {
                showPreview(last_selected_idx);
            } else {
                hidePreview();
            }

            position_to_item(last_selected_idx);
        }
    }
    function jump_down(modifiers: KeyboardModifiers, items: int) {
        if (last_selected_idx != -1) {
            last_selected_idx = (last_selected_idx + items).min(root.values.length - 1);
            // If hit at header, try to skip it
            if (!contains_data(last_selected_idx)) {
                last_selected_idx = (last_selected_idx + 1).min(root.values.length - 1);
            }

            if (!modifiers.shift) {
                start_shift_idx = last_selected_idx;
            }
            
            Callabler.row_select_items_with_shift(start_shift_idx, last_selected_idx);
            if (start_shift_idx == last_selected_idx) {
                showPreview(last_selected_idx);
            } else {
                hidePreview();
            }

            position_to_item(last_selected_idx);
        }
    }

    public function released_key(event: KeyEvent) {
        // debug("Key released: " + event.text + "  CTRL - " + (event.modifiers.control ? "true" : "false") + "  SHIFT - " + (event.modifiers.shift ? "true" : "false") + " ALT - " + (event.modifiers.alt ? "true" : "false"));

        if (event.text == " ") {
            Callabler.row_reverse_checked_selection();
        } else if (event.text == "\n") {
           if (last_selected_idx != -1 && contains_data(last_selected_idx)) {
                Callabler.row_open_item_with_index(last_selected_idx);
           }
        } else if (event.text == Key.UpArrow) {
            jump_up(event.modifiers, 1);
        } else if (event.text == Key.DownArrow) {
            jump_down(event.modifiers, 1);
        } else if (event.text == Key.PageDown) {
            jump_down(event.modifiers, get_number_of_items_to_skip());
        } else if (event.text == Key.PageUp) {
            jump_up(event.modifiers, get_number_of_items_to_skip());
        } else if (event.text == Key.Home) {
            jump_up(event.modifiers, root.values.length);
        } else if (event.text == Key.End) {
            jump_down(event.modifiers, root.values.length);
        }
    }
    public function pressed_key(event: KeyEvent) {
        // debug("Key pressed: " + event.text + "  CTRL - " + (event.modifiers.control ? "true" : "false") + "  SHIFT - " + (event.modifiers.shift ? "true" : "false") + " ALT - " + (event.modifiers.alt ? "true" : "false"));
        
        if ((event.text == "a" || event.text == "A") && event.modifiers.control && !event.modifiers.shift && !event.modifiers.alt && !event.modifiers.meta) {
            Callabler.row_select_all();
        }
    }

    function showPreview(idx: int) {
        Callabler.load_image_preview(root.values[idx].val_str[root.parentPathIdx - 1] + "/" + root.values[idx].val_str[root.fileNameIdx - 1]);
    }

    function hidePreview() {
        Callabler.load_image_preview("NOT_AVAILABLE.NOT_AVAILABLE");
    }
}
